<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>画直线</title>
  <style>
    canvas {
      border: 1px solid;
    }
  </style>
</head>
<body>
   <p>鼠标画直线</p>
  <canvas width="800" height="600"></canvas>
  <script>
  var canvas = document.querySelector('canvas'),
      context = canvas.getContext('2d'),
      isDrag = false,
      startPoint = {},
      restorePoint = {};


  canvas.onmousedown = function () {
    isDrag = true;
    startPoint.x = event.x;
    startPoint.y = event.y;
    restorePoint = context.getImageData(0, 0, canvas.width, canvas.height);
  }

  canvas.onmousemove = function() {
    if(isDrag) {
      context.putImageData(restorePoint, 0, 0);
      context.beginPath();
      context.moveTo(startPoint.x, startPoint.y);
      context.lineTo(event.x, event.y);
      context.stroke();
    }
  }

  canvas.onmouseup = function() {
    isDrag = false;
  }
  </script>
</body>
</html>
